package com.baidu.mapapi.clusterutil;

import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.PowerManager;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.LocRequest;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.fence.FenceAlarmPushInfo;
import com.baidu.trace.api.fence.MonitoredAction;
import com.baidu.trace.api.track.LatestPointRequest;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.model.OnCustomAttributeListener;
import com.baidu.trace.model.OnTraceListener;
import com.baidu.trace.model.ProcessOption;
import com.baidu.trace.model.PushMessage;
import com.baidu.trace.model.StatusCodes;
import com.baidu.track.R;
import com.baidu.track.TrackApplication;
import com.baidu.track.activity.TracingProActivity;
import com.baidu.track.receiver.TrackReceiver;
import com.baidu.track.utils.CommonUtil;
import com.baidu.track.utils.NetUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by Tabjin on 2017/10/11/011.
 */

public class TraceUtil {


    /**
     * 轨迹客户端
     */
    public LBSTraceClient mClient = null;

    /**
     * 轨迹服务
     */
    public Trace mTrace = null;

    /**
     * 轨迹服务ID
     */
    public long serviceId = 148842;

    /**
     * Entity标识
     */
    public String entityName = "quemos";

    public boolean isRegisterReceiver = false;

    /**
     * 服务是否开启标识
     */
    public boolean isTraceStarted = false;

    /**
     * 采集是否开启标识
     */
    public boolean isGatherStarted = false;


    public SharedPreferences trackConf = null;

    private LocRequest locRequest = null;

    private AtomicInteger mSequenceGenerator = new AtomicInteger();

    public Context mContext;

    private TrackApplication trackApp;

    private TraceUtil instance;

    private TraceUtil(Context context,String entityName){
        mContext = context;
        trackApp = (TrackApplication) context;
        this.entityName = entityName;
    }

    public TraceUtil getInstance(Context context,String entityName) {
        if(instance == null){
            instance = new TraceUtil(context,entityName);
        }
        return instance;
    }

    /**
     * 初始化请求客户端
     */
    public void initTrace(){

        SDKInitializer.initialize(mContext);
        mClient = new LBSTraceClient(mContext);
        mTrace = new Trace(serviceId, entityName);

        trackConf = mContext.getSharedPreferences("track_conf", MODE_PRIVATE);
        locRequest = new LocRequest(serviceId);

        mClient.setOnCustomAttributeListener(new OnCustomAttributeListener() {
            @Override
            public Map<String, String> onTrackAttributeCallback() {
                Map<String, String> map = new HashMap<>();
                return map;
            }

            @Override
            public Map<String, String> onTrackAttributeCallback(long locTime) {
                System.out.println("onTrackAttributeCallback, locTime : " + locTime);
                Map<String, String> map = new HashMap<>();
                /*map.put("key1", "value1");
                map.put("key2", "value2");*/
                return map;
            }
        });
    }

    /**
     * 获取当前位置
     */
    public void getCurrentLocation(OnEntityListener entityListener, OnTrackListener trackListener) {
        // 网络连接正常，开启服务及采集，则查询纠偏后实时位置；否则进行实时定位
        if (NetUtil.isNetworkAvailable(mContext)
                && trackConf.contains("is_trace_started")
                && trackConf.contains("is_gather_started")
                && trackConf.getBoolean("is_trace_started", false)
                && trackConf.getBoolean("is_gather_started", false)) {
            LatestPointRequest request = new LatestPointRequest(getTag(), serviceId, entityName);
            ProcessOption processOption = new ProcessOption();
            processOption.setNeedDenoise(true);
            processOption.setRadiusThreshold(100);
            request.setProcessOption(processOption);
            mClient.queryLatestPoint(request, trackListener);
        } else {
            mClient.queryRealTimeLoc(locRequest, entityListener);
        }
    }

    /**
     * 清除Trace状态：初始化app时，判断上次是正常停止服务还是强制杀死进程，根据trackConf中是否有is_trace_started字段进行判断。
     * <p>
     * 停止服务成功后，会将该字段清除；若未清除，表明为非正常停止服务。
     */
    private void clearTraceStatus() {
        if (trackConf.contains("is_trace_started") || trackConf.contains("is_gather_started")) {
            SharedPreferences.Editor editor = trackConf.edit();
            editor.remove("is_trace_started");
            editor.remove("is_gather_started");
            editor.apply();
        }
    }

    /**
     * 获取请求标识
     *
     * @return
     */
    public int getTag() {
        return mSequenceGenerator.incrementAndGet();
    }


    OnTraceListener traceListener = new OnTraceListener() {


        @Override
        public void onBindServiceCallback(int i, String s) {

        }

        /**
         * 开启服务回调接口
         * @param errorNo 状态码
         * @param message 消息
         *                <p>
         *                <pre>0：成功 </pre>
         *                <pre>10000：请求发送失败</pre>
         *                <pre>10001：服务开启失败</pre>
         *                <pre>10002：参数错误</pre>
         *                <pre>10003：网络连接失败</pre>
         *                <pre>10004：网络未开启</pre>
         *                <pre>10005：服务正在开启</pre>
         *                <pre>10006：服务已开启</pre>
         */
        @Override
        public void onStartTraceCallback(int errorNo, String message) {
            if (StatusCodes.SUCCESS == errorNo || StatusCodes.START_TRACE_NETWORK_CONNECT_FAILED <= errorNo) {
                trackApp.isTraceStarted = true;
                SharedPreferences.Editor editor = trackApp.trackConf.edit();
                editor.putBoolean("is_trace_started", true);
                editor.apply();
                registerReceiver();
            }
        }

        /**
         * 停止服务回调接口
         * @param errorNo 状态码
         * @param message 消息
         *                <p>
         *                <pre>0：成功</pre>
         *                <pre>11000：请求发送失败</pre>
         *                <pre>11001：服务停止失败</pre>
         *                <pre>11002：服务未开启</pre>
         *                <pre>11003：服务正在停止</pre>
         */
        @Override
        public void onStopTraceCallback(int errorNo, String message) {
            if (StatusCodes.SUCCESS == errorNo || StatusCodes.CACHE_TRACK_NOT_UPLOAD == errorNo) {
                trackApp.isTraceStarted = false;
                trackApp.isGatherStarted = false;
                // 停止成功后，直接移除is_trace_started记录（便于区分用户没有停止服务，直接杀死进程的情况）
                SharedPreferences.Editor editor = trackApp.trackConf.edit();
                editor.remove("is_trace_started");
                editor.remove("is_gather_started");
                editor.apply();
                unregisterPowerReceiver();
            }
        }

        /**
         * 开启采集回调接口
         * @param errorNo 状态码
         * @param message 消息
         *                <p>
         *                <pre>0：成功</pre>
         *                <pre>12000：请求发送失败</pre>
         *                <pre>12001：采集开启失败</pre>
         *                <pre>12002：服务未开启</pre>
         */
        @Override
        public void onStartGatherCallback(int errorNo, String message) {
            if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STARTED == errorNo) {
                trackApp.isGatherStarted = true;
                SharedPreferences.Editor editor = trackApp.trackConf.edit();
                editor.putBoolean("is_gather_started", true);
                editor.apply();
            }
        }

        /**
         * 停止采集回调接口
         * @param errorNo 状态码
         * @param message 消息
         *                <p>
         *                <pre>0：成功</pre>
         *                <pre>13000：请求发送失败</pre>
         *                <pre>13001：采集停止失败</pre>
         *                <pre>13002：服务未开启</pre>
         */
        @Override
        public void onStopGatherCallback(int errorNo, String message) {
            if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STOPPED == errorNo) {
                trackApp.isGatherStarted = false;
                SharedPreferences.Editor editor = trackApp.trackConf.edit();
                editor.remove("is_gather_started");
                editor.apply();
            }

        }

        @Override
        public void onPushCallback(byte b, PushMessage pushMessage) {

        }

        @Override
        public void onInitBOSCallback(int i, String s) {

        }

    };



    private PowerManager.WakeLock wakeLock = null;
    private PowerManager powerManager = null;
    private TrackReceiver trackReceiver;
    /**
     * 注册广播（电源锁、GPS状态）
     */
    private void registerReceiver() {
        if (trackApp.isRegisterReceiver) {
            return;
        }

        if (null == wakeLock) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
        }
        if (null == trackReceiver) {
            trackReceiver = new TrackReceiver(wakeLock);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(StatusCodes.GPS_STATUS_ACTION);
        trackApp.registerReceiver(trackReceiver, filter);
        trackApp.isRegisterReceiver = true;

    }

    private void unregisterPowerReceiver() {
        if (!trackApp.isRegisterReceiver) {
            return;
        }
        if (null != trackReceiver) {
            trackApp.unregisterReceiver(trackReceiver);
        }
        trackApp.isRegisterReceiver = false;
    }

}
